<template>
  <div class="container">
    <!-- button样式 -->
    <div class="btns">
      <el-button 
      v-has="'sys:user:add'"
      type="primary" icon="el-icon-plus" plain @click="addUser()">
        新增用户
      </el-button>
      <el-button
      v-has="'sys:user:update'"
      type="warning" icon="el-icon-edit" plain @click="handleEdit()">
        编辑用户
      </el-button>
      <el-button
      v-has="'sys:user:delete'"
      type="danger" icon="el-icon-delete" plain @click="del()">
        删除用户
      </el-button>
      <el-button
      v-has="'sys:user:info'"
      type="success" icon="el-icon-search" plain @click="detail()">
        查看用户
      </el-button>
      <el-button
      v-has="'sys:user:addRole'"
      type="primary" icon="el-icon-plus" plain @click="assignment()">
        赋值角色
      </el-button>
      <el-button
      v-has="'sys:user:updatePassword'"
        type="warning"
        icon="el-icon-edit"
        plain
        @click="changeSecret()"
      >
        修改密码
      </el-button>
      <el-button
      v-has="'sys:user:reset'"
      type="danger" icon="el-icon-edit" plain @click="resetSecret()">
        重置密码
      </el-button>
    </div>

    <!-- 搜索框 -->
    <div class="search">
      <el-form
        ref="searchForm"
        :model="searchForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        :inline="true"
      >
        <div class="out_box">
          <div class="form_box_list">
            <!-- 两个搜索框为一个form_box -->
            <div class="form_box">
              <div class="formItem">
                <div class="itmetitle">用户名称</div>
                <div class="iteminput">
                  <el-input
                    v-model="searchForm.userName"
                    placeholder="请输入用户名称"
                  />
                </div>
              </div>
              <div class="formItem">
                <div class="itmetitle">登录名称</div>
                <div class="iteminput">
                  <el-input
                    v-model="searchForm.loginName"
                    placeholder="请输入登录名称"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="item_btn">
            <el-button type="primary" @click="submitsearch('searchForm')">
              查询
            </el-button>
            <el-button @click="resetForm('searchForm')">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <div class="myTable">
      <el-table
        ref="Table"
        :data="userList"
        style="width: 100%; margin-top: 20px;"
        @selection-change="handleSelectionChange"
        @row-click="handleClickTableRow"
      >
        <el-table-column align="center" type="selection" width="80" />
        <el-table-column align="center" label="用户Id" prop="id" />
        <el-table-column align="center" label="登录名称" prop="loginName" />
        <el-table-column align="center" label="用户名称" prop="userName" />
        <el-table-column align="center" label="用户联系方式" prop="phone" />
      </el-table>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogShow"
      center
      :destroy-on-close="true"
      width="25%"
    >
      <el-form ref="Form" label-width="80px" :model="formData" :rules="rules">
        <el-form-item label="登录名称" prop="loginName">
          <el-input
            v-model="formData.loginName"
            placeholder="请输入登录名称"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="formData.userName"
            placeholder="请输入用户名称"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item v-if="formType == 1" label="用户密码" prop="userPassword">
          <el-input
            v-model="formData.userPassword"
            type="password"
            placeholder="请输入8-12位数字加字母组合的用户密码"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item v-if="formType == 3" label="用户密码" prop="userPassword">
          <el-input
            v-model="formData.userPassword"
            placeholder="******"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item
          v-if="formType == 1"
          label="确认密码"
          prop="userPasswords"
        >
          <el-input
            v-model="formData.userPasswords"
            type="password"
            placeholder="请再次确认用户密码"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input
            v-model="formData.phone"
            :placeholder="formType === 3 ? '' : '请输入联系方式'"
            maxlength="11"
          />
        </el-form-item>
        <div class="btsbox">
          <el-button
            v-if="formType != 3"
            type="primary"
            @click="submitForm('Form')"
          >
            {{ btnText }}
          </el-button>
          <el-button v-if="formType != 3" @click="cancle('Form')">
            取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="赋值角色"
      :visible.sync="asignDialogShow"
      center
      :destroy-on-close="true"
      :show-header="false"
    >
      <el-table
        ref="role"
        :data="tableData"
        style="width: 100%; margin-top: 20px;"
        @selection-change="getSelectedList"
      >
        <el-table-column
          align="center"
          type="selection"
          width="80"
        ></el-table-column>
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column
          prop="roleDesc"
          label="角色描述"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
      <div class="btsbox">
        <el-button type="primary" @click="submitRole('Form')">
          {{ btnText }}
        </el-button>
        <el-button @click="close('Form')">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="修改密码"
      :visible.sync="changeShow"
      center
      :destroy-on-close="true"
      width="25%"
    >
      <el-form
        ref="changeSecret"
        label-width="80px"
        :model="changeSecretForm"
        :rules="ruless"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="changeSecretForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="changeSecretForm.password"
            type="password"
            placeholder="请输入8-12位数字加字母组合的新密码"
            maxlength="12"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="checkNewPassword">
          <el-input
            v-model="changeSecretForm.checkNewPassword"
            type="password"
            placeholder="请再次输入新密码"
            maxlength="12"
          />
        </el-form-item>
        <div class="btsbox">
          <el-button type="primary" @click="confirmChange('changeSecret')">
            提交
          </el-button>
          <el-button @click="cancle('changeSecret')">
            取消
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { Message, Loading } from 'element-ui'
import { findUserRole } from '@/api/role'
import {
  findUserAll,
  findUserList,
  addUserInfo,
  deleteUser,
  updateUser,
  assignUser,
  getRoleList,
  updatePassword,
  resetUser,
} from '@/api/user'
import { succMsg, errMsg } from '@/utils/message'
// import MyTransition from './component/transition'
import hasDirective  from '/src/directive/permission/btnPermiss.js'
export default {
  // components: {
  //   MyTransition
  // },
  directives:{
        has:hasDirective
      },
  data() {
    const checkPwd = (rule, value, callback) => {
      if (value === '' || value !== this.formData.userPassword) {
        callback(new Error('两次输入密码必须一致!'))
      } else {
        callback()
      }
    }
    const checkPhone = (rule, value, callback) => {
      if (value.trim() == '') {
        callback()
        return
      } else if (!/^1[34578]\d{9}$/.test(value)) {
        callback(new Error('请输入正确手机号!'))
      } else {
        callback()
      }
    }
    const checkNewPsw = (rule, value, callback) => {
      if (value === '' || value !== this.changeSecretForm.password) {
        callback(new Error('两次输入密码必须一致!'))
      } else {
        callback()
      }
    }
    const changepsw = (rule, value, callback) => {
      if (value.trim() == '') {
        callback()
        return
      } else if (!/^[0-9a-zA-Z_]{1,}$/.test(value)) {
        callback(new Error('密碼由字母数字下划线组成!'))
      } else {
        callback()
      }
    }
    const checkPass = (rule, value, callback) => {
      if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,12}$/.test(value)) {
        callback(new Error('密碼由字母数字组合组成!'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      isActive: false,
      userList: [],
      roleList: [],
      checkboxList: [],
      dialogTitle: '',
      pageNum: 1,
      total: 1,
      choseData: [],
      btnText: '确认',
      roleShow: false,
      roleId: '',
      formData: {
        loginName: '',
        userName: '',
        userPassword: '',
        userPasswords: '',
        phone: '',
      },
      dialogShow: false,
      asignDialogShow: false,
      formType: '',
      rules: {
        id: '',
        loginName: [
          { required: true, message: '登录名称不能为空', trigger: 'blur' },
        ],
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
        ],
        userPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: checkPass, trigger: 'blur' },
        ],
        oldPassword: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' },
        ],
        userPasswords: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: checkPwd, trigger: 'blur' }, // 自定义校验
        ],
        phone: [
          { required: false, message: '手机号不能为空', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }, // 自定义校验
        ],
      },
      ruless: {
        oldPassword: [
          { required: true, message: '旧密码不能为空', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: changepsw, validator: checkPass, trigger: 'blur' },
        ],
        checkNewPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: checkNewPsw, trigger: 'blur' },
        ],
      },
      searchForm: {
        userName: '',
        loginName: '',
        page: '',
      },
      selectedList: [],
      changeSecretForm: {
        id: '',
        loginName: '',
        oldPassword: '',
        password: '',
        checkNewPassword: '',
      },
      changeShow: false,
    }
  },
  created() {
    this.findUserList()
    this.getRoleList()
  },
  methods: {
    async resetSecret() {
      if (this.choseData.length === 0 || this.choseData.length > 1) {
        errMsg('请选择一条数据')
        return
      }
      let par = {
        id: this.choseData[0].id,
        loginName: this.choseData[0].loginName,
      }
      this.$msgbox({
        title: '提示',
        message: `确定重置密码吗?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '重置中...'
            resetUser(par).then((res) => {
              if (res.success) {
                Message({
                  message: res.msg,
                  type: 'success',
                  duration: 2 * 1000,
                })
              }
              instance.confirmButtonLoading = false
              done()
            })
          } else {
            done()
          }
        },
      }).then((action) => {})
    },
    findUserRole(userId) {
      const params = {
        userId,
      }
      findUserRole(params)
        .then((res) => {
          console.log(res)
          if (res.success == true) {
            this.roleList = res.data
          }
        })
        .catch((err) => {})
    },
    getSelectedList(val) {
      this.selectedList = val
    },
    getRoleList() {
      getRoleList()
        .then((res) => {
          console.log(res)
          if (res.success == true) {
            this.tableData = res.data
          }
        })
        .catch((err) => {})
    },
    findUserList() {
      findUserAll().then((res) => {
        this.userList = res.data
        console.log(res.data)
      })
    },
    resetForm(formName) {
      this.searchForm.userName = ''
      this.searchForm.loginName = ''
      this.$refs[formName].resetFields()
      this.findUserList()
    },
    handleSelectionChange(val) {
      console.log(val)
      if (val && val.length && val[0].id) {
        this.findUserRole(val[0].id)
      }

      this.choseData = val
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.formType === 1) {
            let prams = {
              userName: this.formData.userName,
              loginName: this.formData.loginName,
              password: this.formData.userPassword,
              phone: this.formData.phone,
            }
            prams = JSON.stringify(prams)
            console.log(prams)
            addUserInfo(prams).then((res) => {
              console.log(res)
              if (res.success) {
                succMsg(res.msg)
                this.findUserList()
                this.dialogShow = false
                // this.getRoleList(this.total)
                this.$refs[formName].resetFields()
              }
            })
          } else {
            let prams = {
              id: this.formData.id,
              userName: this.formData.userName,
              loginName: this.formData.loginName,
              password: this.formData.userPassword,
              phone: this.formData.phone,
              oldPassword: this.formData.oldPassword,
            }
            prams = JSON.stringify(prams)
            updateUser(prams).then((res) => {
              console.log(res)
              if (res.success) {
                succMsg(res.msg)
                this.findUserList()
                this.dialogShow = false
                this.$refs[formName].resetFields()
              }
            })
          }
        } else {
          return false
        }
      })
    },
    cancle(formName) {
      this.dialogShow = false
      this.changeShow = false
      this.$refs[formName].resetFields()
    },
    close(formName) {
      this.asignDialogShow = false
      this.$refs[formName].resetFields()
    },
    handleClickTableRow(row, event, column) {
      this.$refs.Table.toggleRowSelection(row)
    },
    // 查询
    submitsearch() {
      const params = {
        userName: this.searchForm.userName,
        loginName: this.searchForm.loginName,
      }
      findUserList(params)
        .then((res) => {
          console.log(res)
          if (res.success == true) {
            console.log(res.data.rows)
            this.userList = res.data.rows
          }
        })
        .catch((err) => {})
    },
    // 编辑
    handleEdit() {
      if (this.choseData.length === 0 || this.choseData.length > 1) {
        errMsg('请选择一个用户')
        return
      }
      this.dialogShow = true
      this.dialogTitle = '编辑用户'
      this.formType = 2
      this.formData.id = this.choseData[0].id
      this.formData.loginName = this.choseData[0].loginName
      this.formData.userName = this.choseData[0].userName
      this.formData.userPassword = ''
      this.formData.phone = this.choseData[0].phone
    },
    // 查看详情
    detail() {
      if (this.choseData.length === 0 || this.choseData.length > 1) {
        errMsg('请选择一个用户')
        return
      }
      this.dialogShow = true
      this.dialogTitle = '用户详情'
      this.formType = 3
      this.formData.id = this.choseData[0].id
      this.formData.loginName = this.choseData[0].loginName
      this.formData.userName = this.choseData[0].userName
      this.formData.userPassword = ''
      this.formData.phone = this.choseData[0].phone
    },
    // 删除
    async del() {
      if (this.choseData.length === 0) {
        errMsg('请选择一个用户')
        return
      }
      let ids = []
      this.choseData.map((item) => {
        ids.push(item.id)
      })
      this.$msgbox({
        title: '提示',
        message: `确定删除选中用户?`,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            instance.confirmButtonText = '删除中...'
            deleteUser(ids).then((res) => {
              if (res.success) {
                instance.confirmButtonLoading = false
                done()
                Message({
                  message: '删除成功',
                  type: 'success',
                  duration: 2 * 1000,
                })
                this.findUserList()
              } else {
                Message({
                  message: '删除失败',
                  type: 'error',
                  duration: 2 * 1000,
                })
              }
            })
          } else {
            done()
          }
        },
      }).then((action) => {})
    },
    // 赋值角色
    assignment() {
      if (this.choseData.length === 0 || this.choseData.length > 1) {
        errMsg('请选择一个用户')
        return
      }
      this.asignDialogShow = true
      this.$nextTick(() => {
        this.roleList.map((row) => {
          this.tableData.map((item) => {
            if (item.id == row.id) {
              this.$refs.role.toggleRowSelection(item, true)
            }
          })
        })
      })
    },
    checkbox(val) {
      this.checkboxList = val
    },
    addUser() {
      this.formData.loginName = ''
      this.formData.userName = ''
      this.formData.userPassword = ''
      this.formData.userPasswords = ''
      this.formData.phone = ''
      this.dialogShow = true
      this.dialogTitle = '新增用户'
      this.formType = 1
    },
    addRole(row) {
      this.roleId = row.row.id
      this.roleShow = true
    },
    handleDelete(e) {
      deleteUser([e.row.id]).then((res) => {
        if (res.success) {
          succMsg(res.msg)
          this.userList.splice(e.$index, 1)
        }
      })
    },
    submitRole() {
      if (this.checkboxList.length === '') {
        errMsg('请选择赋值角色')
        return
      }
      let roleIdList = []
      this.selectedList.map((item) => {
        roleIdList.push(item.id)
      })
      assignUser({ id: this.choseData[0].id, roleIdList }).then((res) => {
        console.log(res)
        if (res.success) {
          succMsg('新增成功')
          this.asignDialogShow = false
          this.findUserList()
        } else {
          errMsg('新增失败')
          this.asignDialogShow = false
        }
      })
    },
    changeSecret() {
      if (this.choseData.length > 1 || this.choseData.length == 0) {
        errMsg('请选择一个用户')
      } else {
        this.changeShow = true
        this.changeSecretForm.id = this.choseData[0].id
        this.changeSecretForm.loginName = this.choseData[0].loginName
      }
    },
    confirmChange(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          updatePassword(this.changeSecretForm).then((res) => {
            console.log(res)
            if (res.code == 200) {
              this.$refs[formName].resetFields()
              succMsg(res.msg)
              this.changeShow = false
            }
          })
        }
      })
      return
    },
  },
  watch: {
    'formData.phone': function (curVal, oldVal) {
      if (!curVal) {
        this.formData.phone = ''
        return false
      }
      // 实时把非数字的输入过滤掉
      this.formData.phone = curVal.match(/\d/gi)
        ? curVal.match(/\d/gi).join('')
        : ''
    },
    'formData.userPassword': function (curVal, oldVal) {
      console.log(curVal)
      if (!curVal) {
        this.formData.userPassword = ''
        return false
      }
      this.formData.userPassword = curVal.replace(/[\W]/g, '')
    },
    'formData.loginName': function (curVal, oldVal) {
      console.log(curVal)
      if (!curVal) {
        this.formData.loginName = ''
        return false
      }
      this.formData.loginName = curVal.replace(/[\W]/g, '')
    },
    'formData.userPasswords': function (curVal, oldVal) {
      console.log(curVal)
      if (!curVal) {
        this.formData.userPasswords = ''
        return false
      }
      this.formData.userPasswords = curVal.replace(/[\W]/g, '')
    },
  },
}
</script>

<style scoped>
.container {
  height: 100%;
  padding: 20px;
}
.checkitem {
  margin-top: 20px;
}
/deep/ .el-checkbox-group {
  padding-left: 30%;
}
/deep/.el-checkbox__inner {
  margin-right: 19px;
}
/* 搜索框阴影样式 */
.search {
  margin-top: 20px;
  padding: 30px 20px 30px 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
}
/* 表格阴影样式 */
.myTable {
  margin-top: 30px;
  padding: 1px 20px 30px 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/* 表格样式 */
.out_box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.form_box_list {
  width: 80%;
}
.form_box {
  display: flex;
  justify-content: space-between;
}
.form_box:nth-child(n + 2) {
  margin-top: 20px;
}
.formItem {
  width: 48%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.itmetitle {
  width: 20%;
  font-size: 14px;
  color: #606266;
  font-weight: 700;
  text-align: center;
}
.iteminput {
  width: 80%;
}
/* 搜索重置按钮样式 */
.btn {
  display: inline-block;
  width: 100px;
}
.btn:hover {
  background-color: #e8f4ff;
}
.btn:first-child {
  background-color: #1890ff;
}
.btn_sty:first-child:hover {
  /* background-color: #46a6ff; */
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
.isShowStyle {
  position: absolute;
  width: 7%;
  bottom: -35px;
  left: 45%;
  color: white;
  text-align: center;
  padding: 7px 10px 10px;
  background-image: url('../../assets/imgs/updown-grey.png');
  background-size: contain;
  background-repeat: no-repeat;
}
.btsbox {
  margin-top: 10px;
  width: 100%;
  display: flex;
  justify-content: space-around;
}
</style>
